<template>
  <el-dialog
    v-model="dialogVisible"
    :title="`批量${CategoryManagementUtils.getBatchOperationText(operationType)}`"
    width="600px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <div class="batch-operation-content">
      <!-- 操作说明 -->
      <div class="operation-info">
        <el-alert
          :title="`您即将对 ${selectedCategories.length} 个分类执行${CategoryManagementUtils.getBatchOperationText(operationType)}操作`"
          :type="getAlertType(operationType)"
          :closable="false"
          show-icon
        />
      </div>

      <!-- 分类列表 -->
      <div class="category-list">
        <h4>选中的分类：</h4>
        <div class="category-items">
          <div
            v-for="category in selectedCategories"
            :key="category.id"
            class="category-item"
          >
            <div class="category-info">
              <img
                v-if="category.icon"
                :src="CategoryManagementUtils.generateIconUrl(category.icon)"
                class="category-icon"
                @error="handleIconError"
              />
              <div class="category-details">
                <span class="category-name">{{ category.name }}</span>
                <span class="category-desc">{{ category.description }}</span>
              </div>
            </div>
            <div class="category-status">
              <el-tag
                :type="
                  CategoryManagementUtils.getStatusTagType(category.status)
                "
              >
                {{ CategoryManagementUtils.getStatusText(category.status) }}
              </el-tag>
              <span class="article-count"
                >{{ category.articleCount || 0 }} 篇文章</span
              >
            </div>
          </div>
        </div>
      </div>

      <!-- 操作参数 -->
      <div v-if="needsParameters" class="operation-params">
        <el-form :model="form" label-width="100px">
          <el-form-item
            v-if="operationType === 'ENABLE' || operationType === 'DISABLE'"
            label="操作原因"
          >
            <el-input
              v-model="form.reason"
              type="textarea"
              placeholder="请输入操作原因（可选）"
              :rows="3"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 警告信息 -->
      <div v-if="operationType === 'DELETE'" class="warning-info">
        <el-alert title="删除警告" type="error" :closable="false" show-icon>
          <template #default>
            <div>
              <p>删除操作不可恢复，请确认以下事项：</p>
              <ul>
                <li>被文章使用的分类无法删除</li>
                <li>删除后相关数据将永久丢失</li>
                <li>建议先备份重要数据</li>
              </ul>
            </div>
          </template>
        </el-alert>
      </div>

      <!-- 确认输入 -->
      <div v-if="operationType === 'DELETE'" class="confirm-input">
        <el-form label-width="100px">
          <el-form-item label="确认删除">
            <el-input
              v-model="confirmText"
              placeholder="请输入 DELETE 确认删除"
              @input="handleConfirmInput"
            />
            <div class="confirm-tips">
              请输入 <code>DELETE</code> 确认删除操作
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button
          :type="getButtonType(operationType)"
          :disabled="!canConfirm"
          @click="handleConfirm"
        >
          确认{{ CategoryManagementUtils.getBatchOperationText(operationType) }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import {
  type CategoryInfo,
  CategoryManagementUtils
} from "@/api/category-management";

interface Props {
  visible: boolean;
  operationType: string;
  selectedCategories: CategoryInfo[];
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  operationType: "ENABLE",
  selectedCategories: () => []
});

const emit = defineEmits<{
  "update:visible": [value: boolean];
  confirm: [params: any];
}>();

const dialogVisible = ref(false);
const confirmText = ref("");

// 表单数据
const form = reactive({
  reason: ""
});

// 监听对话框显示状态
watch(
  () => props.visible,
  newVal => {
    dialogVisible.value = newVal;
    if (newVal) {
      resetForm();
    }
  },
  { immediate: true }
);

watch(dialogVisible, newVal => {
  emit("update:visible", newVal);
});

// 计算属性
const needsParameters = computed(() => {
  return ["ENABLE", "DISABLE"].includes(props.operationType);
});

const canConfirm = computed(() => {
  if (props.operationType === "DELETE") {
    return confirmText.value === "DELETE";
  }
  return true;
});

// 方法
const getAlertType = (type: string) => {
  const typeMap: Record<string, string> = {
    ENABLE: "success",
    DISABLE: "warning",
    DELETE: "error"
  };
  return typeMap[type] || "info";
};

const getButtonType = (type: string) => {
  const typeMap: Record<string, string> = {
    ENABLE: "success",
    DISABLE: "warning",
    DELETE: "danger"
  };
  return typeMap[type] || "primary";
};

const resetForm = () => {
  form.reason = "";
  confirmText.value = "";
};

const handleIconError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  // 防止无限循环，检查是否已经是默认图标
  if (img.src.includes("data:image/svg+xml")) {
    return;
  }

  // 使用内联SVG作为默认图标，避免网络请求
  const defaultIcon =
    "data:image/svg+xml;base64," +
    btoa(`
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#909399" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
      <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
    </svg>
  `);

  img.src = defaultIcon;
};

const handleConfirmInput = (value: string) => {
  confirmText.value = value.toUpperCase();
};

const handleConfirm = () => {
  const params = {
    categoryIds: props.selectedCategories.map(c => c.id),
    operation: props.operationType,
    reason: form.reason || undefined
  };

  // 根据操作类型添加特定参数
  if (props.operationType === "ENABLE") {
    params.targetStatus = 1;
  } else if (props.operationType === "DISABLE") {
    params.targetStatus = 0;
  }

  emit("confirm", params);
  handleCancel();
};

const handleCancel = () => {
  dialogVisible.value = false;
};
</script>

<style scoped>
.batch-operation-content {
  max-height: 500px;
  overflow-y: auto;
}

.operation-info {
  margin-bottom: 20px;
}

.category-list {
  margin-bottom: 20px;
}

.category-list h4 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.category-items {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.category-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border-bottom: 1px solid #f0f2f5;
}

.category-item:last-child {
  border-bottom: none;
}

.category-info {
  display: flex;
  flex: 1;
  gap: 8px;
  align-items: center;
}

.category-icon {
  width: 24px;
  height: 24px;
  object-fit: cover;
}

.category-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.category-name {
  font-weight: 500;
  color: #303133;
}

.category-desc {
  font-size: 12px;
  color: #909399;
}

.category-status {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: flex-end;
}

.article-count {
  font-size: 12px;
  color: #909399;
}

.operation-params {
  margin-bottom: 20px;
}

.warning-info {
  margin-bottom: 20px;
}

.warning-info ul {
  padding: 0;
  margin: 8px 0 0 20px;
}

.warning-info li {
  margin-bottom: 4px;
  color: #f56c6c;
}

.confirm-input {
  margin-bottom: 20px;
}

.confirm-tips {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

.confirm-tips code {
  padding: 2px 4px;
  font-weight: 600;
  color: #e6a23c;
  background-color: #f5f7fa;
  border-radius: 2px;
}

.dialog-footer {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}
</style>
